package Service;

import java.util.ArrayList;

import Dao.GameDao;
import pojo.Chess;
import pojo.Game;
import pojo.User;

public class GameService {
	private GameDao gameDao = GameDao.getInstance();
	
	private static GameService gameService = new GameService();
	private GameService() {}
	public static GameService getInstance() {return gameService;}
	
	public boolean add(Game game) {//新对局开始
		return gameDao.add(game);
	}
	
	//设置winner
	public boolean cover(Game game) {
		return this.gameDao.cover(game);
	}
	
	public int[][] turn(Game game){
		int[][] arr = new int[16][16];//0-15
		if((game!=null)&&(game.getChesses()!=null)) {
			for(Chess c:game.getChesses()) {
				arr[c.getX()][c.getY()] = c.getBlack()? 1:-1;
			}
		}
		return arr;
	}
	
	//判断16*16是否游戏结束
	public int judge(int[][] arr,int x,int y) {
		int flag = arr[x][y];
		boolean goonx=true,goony=true;
		int step = 0;
		//横向
		for(int i=1;goonx||goony ;i++) {
			if(goonx&&x+i<16&&arr[x+i][y] == flag) step++;
			else goonx = false;
			if(goony&&x-i>=0&&arr[x-i][y] == flag) step++;
			else goony = false;
		}
		if(step>3)return arr[x][y];
		//纵向
		goonx=true;goony=true;step=0;
		for(int i=1;goonx||goony ;i++) {
			if(goonx&&y+i<16&&y+i>=0&&arr[x][y+i] == flag)step++;
			else goonx = false;
			if(goony&&y-i>=0&&y-i<16&&arr[x][y-i] == flag)step++;
			else goony = false;
		}
		if(step>3)return arr[x][y];
		//右斜
		goonx=true;goony=true;step=0;
		for(int i=1;goonx||goony ;i++) {
			if(goonx&&x-i>=0&&y-i>=0&&arr[x-i][y-i] == flag) step++;
			else goonx = false;
			if(goony&&x+i<16&&y+i<16&&arr[x+i][y+i] == flag) step++;
			else goony = false;
		}
		if(step>3)return arr[x][y];
		//左斜
		goonx=true;goony=true;step=0;
		for(int i=1;goonx||goony ;i++) {
			if(goonx&&x+i<16&&y-i>=0&&arr[x+i][y-i] == flag) step++;
			else goonx = false;
			if(goony&&x-i>=0&&y+i<16&&arr[x-i][y+i] == flag) step++;
			else goony = false;
		}
		if(step>3)return arr[x][y];
		
		return 0;
	}
	
	public ArrayList<Game> list(){
		return this.gameDao.list();
	}
	public Game update(Game game,Chess chess) {
		return gameDao.update(game, chess);
	}
}
